package com.lagou.flashsale.service.impl;

import com.lagou.flashsale.entity.Order;
import com.lagou.flashsale.entity.OrderStatus;
import com.lagou.flashsale.service.OrderService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate<String, Integer> redisTemplate;

    @Override
    public boolean order(Order order) {
        // 生成订单ID
        order.setOrderId(UUID.randomUUID().toString());

        Integer goodsCount = redisTemplate.opsForValue().get("goods_count");

        if (goodsCount <= 0) return false;

        rocketMQTemplate.asyncSend("tp_flashsale", order, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                redisTemplate.opsForValue().set("goods_count", goodsCount - 1);
                System.out.println(order);
                order.setOrderStatus(OrderStatus.NEW);
            }

            @Override
            public void onException(Throwable throwable) {
            }
        });

        return order.getOrderStatus() == null ? false : true;
    }
}
